找传奇、传世资源到传世资源站!

VC写的一个串口通讯例子

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

from clipboard
//Download by http://www.NewXing.comusing System;using System.Drawing;using System.Collections;using System.Windows.Forms;using System.Data;using System.Runtime.InteropServices; using System.Threading;namespace SerialAPI { /// <summary> /// SerialPort 的摘要说明。 /// </summary> public class SerialPort { #region 申明要引用的和串口调用有关的API //win32 api constants private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const int OPEN_EXISTING = 3; private const int INVALID_HANDLE_VALUE = -1; private const int MAXBLOCK = 4096; private const uint PURGE_TXABORT = 0x0001; // Kill the pending/current writes to the comm port. private const uint PURGE_RXABORT = 0x0002; // Kill the pending/current reads to the comm port. private const uint PURGE_TXCLEAR = 0x0004; // Kill the transmit queue if there. private const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there. [StructLayout(LayoutKind.Sequential)] private struct DCB { //taken from c struct in platform sdk public int DCBlength; // sizeof(DCB) public int BaudRate; // current baud rate public int fBinary; // binary mode, no EOF check public int fParity; // enable parity checking public int fOutxCtsFlow; // CTS output flow control public int fOutxDsrFlow; // DSR output flow control public int fDtrControl; // DTR flow control type public int fDsrSensitivity; // DSR sensitivity public int fTXContinueOnXoff; // XOFF continues Tx public int fOutX; // XON/XOFF out flow control public int fInX; // XON/XOFF in flow control public int fErrorChar; // enable error replacement public int fNull; // enable null stripping public int fRtsControl; // RTS flow control public int fAbortOnError; // abort on error public int fDummy2; // reserved public ushort wReserved; // not currently used public ushort XonLim; // transmit XON threshold public ushort XoffLim; // transmit XOFF threshold public byte ByteSize; // number of bits/byte, 4-8 public byte Parity; // 0-4=no,odd,even,mark,space public byte StopBits; // 0,1,2 = 1, 1.5, 2 public char XonChar; // Tx and Rx XON character public char XoffChar; // Tx and Rx XOFF character public char ErrorChar; // error replacement character public char EofChar; // end of input character public char EvtChar; // received event character public ushort wReserved1; // reserved; do not use } [StructLayout(LayoutKind.Sequential)] private struct COMMTIMEOUTS { public int ReadIntervalTimeout; public int ReadTotalTimeoutMultiplier; public int ReadTotalTimeoutConstant; public int WriteTotalTimeoutMultiplier; public int WriteTotalTimeoutConstant; } [StructLayout(LayoutKind.Sequential)] private struct OVERLAPPED { public int Internal; public int InternalHigh; public int Offset; public int OffsetHigh; public int hEvent; } [StructLayout(LayoutKind.Sequential)] private struct COMSTAT { /*public int fCtsHold; public int fDsrHold; public int fRlsdHold; public int fXoffHold; public int fXoffSent; public int fEof; public int fTxim; public int fReserved; public int cbInQue; public int cbOutQue;*/ // Should have a reverse, i don't know why!!!!! public int cbOutQue; public int cbInQue; public int fReserved; public int fTxim; public int fEof; public int fXoffSent; public int fXoffHold; public int fRlsdHold; public int fDsrHold; public int fCtsHold; } #if FULLFRAMEWORK [DllImport("kernel32")] private static extern int CreateFile( string lpFileName, // file name uint dwDesiredAccess, // access mode int dwShareMode, // share mode int lpSecurityAttributes, // SD int dwCreationDisposition, // how to create int dwFlagsAndAttributes, // file attributes int hTemplateFile // handle to template file ); #else [DllImport("coredll")] private static extern int CreateFile( string lpFileName, // file name uint dwDesiredAccess, // access mode int dwShareMode, // share mode int lpSecurityAttributes, // SD int dwCreationDisposition, // how to create int dwFlagsAndAttributes, // file attributes int hTemplateFile // handle to template file ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool GetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); #else [DllImport("coredll")] private static extern bool GetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool BuildCommDCB( string lpDef, // device-control string ref DCB lpDCB // device-control block ); #else [DllImport("coredll")] private static extern bool BuildCommDCB( string lpDef, // device-control string ref DCB lpDCB // device-control block ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool SetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); #else [DllImport("coredll")] private static extern bool SetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool GetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); #else [DllImport("coredll")] private static extern bool GetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool SetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); #else [DllImport("coredll")] private static extern bool SetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool ReadFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToRead, // number of bytes to read ref int lpNumberOfBytesRead, // number of bytes read ref OVERLAPPED lpOverlapped // overlapped buffer ); #else [DllImport("coredll")] private static extern bool ReadFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToRead, // number of bytes to read ref int lpNumberOfBytesRead, // number of bytes read ref OVERLAPPED lpOverlapped // overlapped buffer ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool WriteFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToWrite, // number of bytes to write ref int lpNumberOfBytesWritten, // number of bytes written ref OVERLAPPED lpOverlapped // overlapped buffer ); #else [DllImport("coredll")] private static extern bool WriteFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToWrite, // number of bytes to write ref int lpNumberOfBytesWritten, // number of bytes written ref OVERLAPPED lpOverlapped // overlapped buffer ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool CloseHandle( int hObject // handle to object ); #else [DllImport("coredll")] private static extern bool CloseHandle( int hObject // handle to object ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool ClearCommError( int hFile, // handle to file ref int lpErrors, ref COMSTAT lpStat ); #else [DllImport("coredll")] private static extern bool ClearCommError( int hFile, // handle to file ref int lpErrors, ref COMSTAT lpStat ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool PurgeComm( int hFile, // handle to file uint dwFlags ); #else [DllImport("coredll")] private static extern bool PurgeComm( int hFile, // handle to file uint dwFlags ); #endif #if FULLFRAMEWORK [DllImport("kernel32")] private static extern bool SetupComm( int hFile, int dwInQueue, int dwOutQueue ); #else [DllImport("coredll")] private static extern bool SetupComm( int hFile, int dwInQueue, int dwOutQueue ); #endif #endregion // SerialPort的成员变量 private int hComm = INVALID_HANDLE_VALUE; private bool bOpened = false; public bool Opened { get { return bOpened; } } /// <summary> ///串口的初始化函数 ///lpFileName 端口名 ///baudRate 波特率 ///parity 校验位 ///byteSize 数据位 ///stopBits 停止位 /// <summary> public bool OpenPort(string lpFileName,int baudRate,byte parity, byte byteSize, byte stopBits) { // OPEN THE COMM PORT. hComm = CreateFile(lpFileName ,GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); // IF THE PORT CANNOT BE OPENED, BAIL OUT. if(hComm == INVALID_HANDLE_VALUE) { return false; } SetupComm(hComm, MAXBLOCK, MAXBLOCK); // SET THE COMM TIMEOUTS. COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); GetCommTimeouts(hComm,ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = Int32.MaxValue; ctoCommPort.ReadTotalTimeoutConstant = 0; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutConstant = 1000; SetCommTimeouts(hComm,ref ctoCommPort); // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST. // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING. // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING. DCB dcbCommPort = new DCB(); dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort); GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate = baudRate; dcbCommPort.Parity = parity; dcbCommPort.ByteSize = byteSize; dcbCommPort.StopBits = stopBits; SetCommState(hComm, ref dcbCommPort); PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT); PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT); bOpened = true; return true; } // 关闭串口 public bool ClosePort() { if (hComm == INVALID_HANDLE_VALUE) { return false; } if (CloseHandle(hComm)) { hComm = INVALID_HANDLE_VALUE; bOpened = false; return true; } else { return false; } } // 往串口写数据 public bool WritePort(byte[] WriteBytes) { if (hComm == INVALID_HANDLE_VALUE) { return false; } COMSTAT ComStat = new COMSTAT(); int dwErrorFlags = 0; ClearCommError(hComm, ref dwErrorFlags, ref ComStat); if (dwErrorFlags != 0) PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT); OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesWritten = 0; return WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort); } // 从串口读数据 public int ReadPort(int NumBytes, byte[] commRead) { if (hComm == INVALID_HANDLE_VALUE) { return 0; } COMSTAT ComStat = new COMSTAT(); int dwErrorFlags = 0; ClearCommError(hComm, ref dwErrorFlags, ref ComStat); if (dwErrorFlags != 0) {PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT); }if (ComStat.cbInQue > 0) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesRead = 0; ReadFile(hComm, commRead, NumBytes, ref BytesRead, ref ovlCommPort); return BytesRead;} else { return 0; } } } } namespace CSharpSerialPort{/// <summary>/// Form1 的摘要说明。/// </summary>public class Form1 : System.Windows.Forms.Form{private System.Windows.Forms.MenuItem menuItem1;private System.Windows.Forms.MenuItem menuItem2;private System.Windows.Forms.Button button1;private System.Windows.Forms.MainMenu mainMenu1;private System.Windows.Forms.TextBox textBoxReceive;private System.Windows.Forms.Button button2;private SerialAPI.SerialPort Serial=new SerialAPI.SerialPort();bool PortOpen=false;private System.Windows.Forms.TextBox textBoxSend;private System.Windows.Forms.Label label1;private Microsoft.WindowsCE.Forms.InputPanel inputPanel1;private System.Windows.Forms.Label label2;private System.Windows.Forms.CheckBox checkBox1;bool Receive=false;private System.Windows.Forms.Timer timer1;private char last_key;private System.Windows.Forms.MenuItem menuItem3;private System.Windows.Forms.Label label4;private int loopnum;private System.Windows.Forms.Label label5;private int baudRate;private System.Windows.Forms.Label label6;private System.Windows.Forms.Label returnnum;private System.Windows.Forms.Button button3;private System.Windows.Forms.Button button4;private int delay;public Form1(){//// Windows 窗体设计器支持所必需的//InitializeComponent();//// TODO: 在 InitializeComponent 调用后添加任何构造函数代码//}/// <summary>/// 清理所有正在使用的资源。/// </summary>protected override void Dispose( bool disposing ){base.Dispose( disposing );}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要使用代码编辑器修改/// 此方法的内容。/// </summary>private void InitializeComponent(){this.mainMenu1 = new System.Windows.Forms.MainMenu();this.menuItem1 = new System.Windows.Forms.MenuItem();this.menuItem2 = new System.Windows.Forms.MenuItem();this.menuItem3 = new System.Windows.Forms.MenuItem();this.button1 = new System.Windows.Forms.Button();this.textBoxReceive = new System.Windows.Forms.TextBox();this.button2 = new System.Windows.Forms.Button();this.textBoxSend = new System.Windows.Forms.TextBox();this.label1 = new System.Windows.Forms.Label();this.inputPanel1 = new Microsoft.WindowsCE.Forms.InputPanel();this.label2 = new System.Windows.Forms.Label();this.returnnum = new System.Windows.Forms.Label();this.checkBox1 = new System.Windows.Forms.CheckBox();this.timer1 = new System.Windows.Forms.Timer();this.label4 = new System.Windows.Forms.Label();this.label5 = new System.Windows.Forms.Label();this.label6 = new System.Windows.Forms.Label();this.button3 = new System.Windows.Forms.Button();this.button4 = new System.Windows.Forms.Button();// // mainMenu1// this.mainMenu1.MenuItems.Add(this.menuItem1);// // menuItem1// this.menuItem1.MenuItems.Add(this.menuItem2);this.menuItem1.MenuItems.Add(this.menuItem3);this.menuItem1.Text = "操作";// // menuItem2// this.menuItem2.Text = "退出";this.menuItem2.Click = new System.EventHandler(this.menuItem2_Click);// // menuItem3// this.menuItem3.Text = "设置串口";this.menuItem3.Click = new System.EventHandler(this.menuItem3_Click);// // button1// this.button1.Location = new System.Drawing.Point(88, 184);this.button1.Size = new System.Drawing.Size(56, 24);this.button1.Text = "发送";this.button1.Click = new System.EventHandler(this.button1_Click);// // textBoxReceive// this.textBoxReceive.Location = new System.Drawing.Point(24, 22);this.textBoxReceive.Multiline = true;this.textBoxReceive.Size = new System.Drawing.Size(192, 98);this.textBoxReceive.Text = "";// // button2// this.button2.Location = new System.Drawing.Point(8, 184);this.button2.Size = new System.Drawing.Size(64, 24);this.button2.Text = "打开";this.button2.Click = new System.EventHandler(this.button2_Click);// // textBoxSend// this.textBoxSend.Location = new System.Drawing.Point(24, 152);this.textBoxSend.Size = new System.Drawing.Size(192, 21);this.textBoxSend.Text = "01 01 02 06 05 01 09 00 00 25 08 00 00 01 10 66 66 66 66 FF ";this.textBoxSend.TextChanged = new System.EventHandler(this.textBoxSend_TextChanged);// // label1// this.label1.Location = new System.Drawing.Point(23, 4);this.label1.Size = new System.Drawing.Size(72, 16);this.label1.Text = "接收区";// // label2// this.label2.Location = new System.Drawing.Point(24, 128);this.label2.Size = new System.Drawing.Size(64, 16);this.label2.Text = "发送区";// // returnnum// this.returnnum.Location = new System.Drawing.Point(88, 216);this.returnnum.Size = new System.Drawing.Size(48, 16);this.returnnum.Text = "0";// // checkBox1// this.checkBox1.Location = new System.Drawing.Point(88, 128);this.checkBox1.Size = new System.Drawing.Size(80, 16);this.checkBox1.Text = "十六进制";// // timer1// this.timer1.Interval = 1500;this.timer1.Tick = new System.EventHandler(this.timer1_Tick);// // label4// this.label4.Location = new System.Drawing.Point(136, 216);this.label4.Size = new System.Drawing.Size(48, 16);this.label4.Text = "label4";// // label5// this.label5.Location = new System.Drawing.Point(184, 216);this.label5.Size = new System.Drawing.Size(48, 16);this.label5.Text = "label5";// // label6// this.label6.Location = new System.Drawing.Point(40, 216);this.label6.Size = new System.Drawing.Size(48, 16);this.label6.Text = "label6";// // button3// this.button3.Location = new System.Drawing.Point(0, 128);this.button3.Size = new System.Drawing.Size(24, 16);this.button3.Text = "button3";this.button3.Click = new System.EventHandler(this.button3_Click);// // button4// this.button4.Location = new System.Drawing.Point(152, 184);this.button4.Size = new System.Drawing.Size(72, 24);this.button4.Text = "更改设置";this.button4.Click = new System.EventHandler(this.button4_Click);// // Form1// this.ClientSize = new System.Drawing.Size(234, 232);this.Controls.Add(this.button4);this.Controls.Add(this.button3);this.Controls.Add(this.label6);this.Controls.Add(this.label5);this.Controls.Add(this.label4);this.Controls.Add(this.checkBox1);this.Controls.Add(this.returnnum);this.Controls.Add(this.label2);this.Controls.Add(this.label1);this.Controls.Add(this.textBoxSend);this.Controls.Add(this.button2);this.Controls.Add(this.textBoxReceive);this.Controls.Add(this.button1);this.Menu = this.mainMenu1;this.MinimizeBox = false;this.Text = "Form1";this.Load = new System.EventHandler(this.Form1_Load);}#endregion/// <summary>/// 应用程序的主入口点。/// </summary>static void Main() {Application.Run(new Form1());}private void menuItem2_Click(object sender, System.EventArgs e){Receive=false;Serial.ClosePort();this.Close();}private void SendCmd(){byte[] buf;textBoxReceive.Text ="";if(textBoxSend.TextLength==0){return;}if(checkBox1.Checked ==true){buf = new byte[(textBoxSend.Text.Length/3)];for ( int i=0 ; i< (textBoxSend.Text.Length/3); i ){buf[i] = byte.Parse( textBoxSend.Text.Substring(i*3 ,2) ,System.Globalization.NumberStyles.AllowHexSpecifier);}//com.Output = buf;}else{buf=new byte [textBoxSend.TextLength];for(int i=0;i<textBoxSend.TextLength;i ){buf[i]=Convert.ToByte(textBoxSend.Text[i]);}//byte[] buf=new byte[4]; //buf[0]=200; //buf[1]=0;//buf[2]=0;//buf[3]=200;}Serial.WritePort(buf);}private void button1_Click(object sender, System.EventArgs e){//for(int i=0;i<5;i )//{//SendCmd();//Sleep(500);//}loopnum=0;timer1.Enabled =true;timer1.Interval=delay;}private void timer1_Tick(object sender, System.EventArgs e){loopnum=loopnum 1;label6.Text =loopnum.ToString();if(int.Parse(returnnum.Text)<10 && loopnum<300) //int.Parse(returnnum.Text)<4 && {SendCmd();}else{returnnum.Text ="0";timer1.Enabled =false;}}private void button2_Click(object sender, System.EventArgs e){if(!PortOpen){if(Serial.OpenPort("COM1:",baudRate,0,8,1)){PortOpen=true;Receive=true;ThreadPool.QueueUserWorkItem(new WaitCallback(SerialReceive),0); button2.Text="关闭";}}else{Receive=false;Serial.ClosePort();PortOpen=false;button2.Text="打开";}}public void SerialReceive(Object a){byte [] buf;buf=new byte [1];int bytesRead=0;int i;while(Receive){if(Serial.Opened){bytesRead=Serial.ReadPort(1,buf);if(bytesRead>0){for(i=0;i<bytesRead;i ){//textBoxReceive.Text =Convert.ToChar(buf[i]).ToString();textBoxReceive.Text = buf[i].ToString("X2") " ";}returnnum.Text = textBoxReceive.Text.Length.ToString();}//Application.DoEvents();}}//Thread.Sleep(0);}private void textBoxSend_TextChanged(object sender, System.EventArgs e){//// Hex格式发送数据区输入数据整理:自动用空格间隔每字节的数据//// 转换为大写textBoxSend.Text = textBoxSend.Text.ToUpper();if ( (textBoxSend.Text.Length % 3) == 2 ){if(last_key=='\b')textBoxSend.Text = textBoxSend.Text.Remove( textBoxSend.Text.Length-1 ,1 );elsetextBoxSend.Text = " ";} // 设置插入点到最后面textBoxSend.SelectionStart = textBoxSend.Text.Length;}private void menuItem3_Click(object sender, System.EventArgs e){cResult r = new cResult();r.TextChanged = new TextChangedHandler(this.EventResultChanged);frmComSet fc = new frmComSet(r);fc.ShowDialog();label4.Text = r.Result1;// "\r\n" r.Result2;baudRate=int.Parse(r.Result1);label5.Text = r.Result2;delay=int.Parse(r.Result2);}private void EventResultChanged(string s){label4.Text = s;}private void Form1_Load(object sender, System.EventArgs e){baudRate=9600;delay=1500;label4.Text = baudRate.ToString();label5.Text =delay.ToString();}private void button3_Click(object sender, System.EventArgs e){//ADOCE.Connection connection;// Set connection = CreateObject("ADOCE.Connection.3.1")// connection.ConnectionString = "Data Source=\MyDatabase.cdb"// connection.Open}private void button4_Click(object sender, System.EventArgs e){SendCmd();}}}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复